// 评论模块的路由

var express = require('express');
var router = express.Router();

var moment = require('moment');

const { aesDecrypt, checkSession } = require('../utils/index');
const { MoviesModel, CommentModel } = require('../utils/model')

router.get('/test', function (req, res) {
    res.send('test for the comment')
})

router.get('/mdetail', function (req, res) {
    const { mid } = req.query;
    checkSession(req, res, username => {
        MoviesModel.findOne({
            id: mid
        })
            .then(result => {
                res.render('movieDetail', {
                    username,
                    result
                })
            })
    })
})

// 提交评论
router.post('/submit', function (req, res) {
    const { mid } = req.query;
    var body = req.body;
    // console.log(body);

    checkSession(req, res, username => {
        MoviesModel.findOne({
            id: mid
        })
            .then(movie => {
                body.time = moment().format('YYYY-MM-DD HH:mm:ss')
                body.movie = movie
                body.author = username
                body.mid = mid
                CommentModel.insertMany(body)
                    .then(result => {
                        res.redirect('/comment/mlist')
                    })
            })
    })
})

// 评论列表
router.get('/mlist', function (req, res) {
    checkSession(req, res, username => {
        // 分页查询
        var page = req.query.page * 1 || 1;
        var pageSize = req.query.pageSize * 1 || 3;
        var total = 0;
        var totalPage = 0;
        CommentModel.find({}, {})
            .then(data => {
                total = data.length;
                totalPage = Math.ceil(total / pageSize);
                page = page < 1 ? 1 : page;
                page = page > totalPage ? totalPage : page;

                if (total > 0) {
                    CommentModel.find({}, {})
                    .skip((page - 1) * pageSize)
                    .limit(pageSize)
                    .sort({ _id: -1 })
                    .then(result => {
                        // console.log(result);
                        result = result.map(item => {
                            /**
                             * 这样子改不了
                             * console.log(moment(item.time).format('YYYY-MM-DD HH:mm:ss'));
                             * item.time = moment(item.time).format('YYYY-MM-DD HH:mm:ss')
                             */

                            // console.log({ ...item });  // 解构会发现，item 外面包了一层 _doc
                            item = { ...item._doc, time: moment(item.time).format('YYYY-MM-DD HH:mm:ss') }
                            return item
                        })
                        res.render('movieList', { username, result, page, pageSize, total, totalPage })
                    })
                } else {
                    res.render('movieList', { username, result: [], page, pageSize})
                }
                
            })
        
        
        // 查询
        // CommentModel.find({}, { _id: 0 })
        //     .sort({ _id: -1 })
        //     .then(result => {
        //         result = result.map(item => {
        //             console.log(moment(item.time).format('YYYY-MM-DD HH:mm:ss'));
        //             item.time = moment(item.time).format('YYYY-MM-DD HH:mm:ss')
        //             console.log(item);
        //             return item
        //         })
        //         res.render('movieList', { username, result })
        //     })
    })
})

// 评论详情
router.get('/cdetail', (req, res) => {
    checkSession(req, res, username => {
        const { _id } = req.query;
        CommentModel.findOne({
            _id
        })
            .then(result => {
                result = { ...result._doc, time: moment(result.time).format('YYYY-MM-DD HH:mm:ss') }
                res.render('commentDetail', {
                    username,
                    result: result.movie,
                    data: result
                })
            })
    })
})

// 用户的评论列表
router.get('/pcommentlist', (req, res) => {
    checkSession(req, res, username => {
        const { author } = req.query;
        CommentModel.find({
            author
        })
            .sort({ _id: -1})
            .then(result => {
                result = result.map(item => {
                    // console.log({ ...item });  // 解构会发现，item 外面包了一层 _doc
                    item = { ...item._doc, time: moment(item.time).format('YYYY-MM-DD HH:mm:ss') }
                    return item
                })
                // console.log(result);
                res.render('persionComment', { username, author, result })
            })
    })
})

// 电影评论列表
router.get('/mcommentlist', (req, res) => {
    checkSession(req, res, username => {
        const { mid } = req.query;
        CommentModel.find({
            mid
        })
            .sort({ _id: -1})
            .then(result => {
                result = result.map(item => {
                    // console.log({ ...item });  // 解构会发现，item 外面包了一层 _doc
                    item = { ...item._doc, time: moment(item.time).format('YYYY-MM-DD HH:mm:ss') }
                    return item
                })
                res.render('movieComment', { username, movie: result[0].movie, result })
                })
    })
})

// 删除电影评论
router.post('/delonecomment', (req, res) => {
    checkSession(req, res, username => {
        const { _id } = req.body;
        CommentModel.remove({
            _id
        })
            .then(result => {
                res.json({
                    code: 200,
                    result,
                    type: 1,
                    msg: "删除成功"
                })
            })
    })
})

// 修改电影评论
router.post('/updateonecomment', (req, res) => {
    checkSession(req, res, username => {
        const { _id, title, content } = req.body;
        CommentModel.updateMany({
            _id
        }, {
            $set: {
                title, content, time: new Date()
            }
        })
            .then(result => {
                res.json({
                    code: 200,
                    result,
                    type: 1,
                    msg: "修改成功"
                })
            })
    })
})


var multiparty = require("multiparty")
var fs = require("fs")
// 上传图片  
router.post("/uploadImg",(req,res)=>{
    const form = new multiparty.Form();  // 自定义表单对象  
    form.encoding = "utf-8"
    form.uploadDir = "./uploadtemp"  // 临时文件中转站
    form.maxFilesSize = 8*1024*1024;  // 8M 
    form.parse(req,function(err,fields,files){
        if(err) {
            console.log(err)
            res.send("<script>alert('图片过大,请重新上传');location.href='/movies'</script>")
        }
        var uploadUrl = "/images/upload/",
        file  = files['filedata'], // 图片信息
        originalFilename = file[0].originalFilename, // 文件名  zkl.jpg 
        tempath = file[0].path;
        var timestamp = new Date().getTime(); // 时间戳  为了避免图片名字冲突 
        uploadUrl += timestamp+originalFilename;  // zkl.jpg ==> 15112341231zkl.jpg
        var newPath = "./public"+uploadUrl;  // 最后路径 
        var fileRead = fs.createReadStream(tempath);  // 可读流 
        var fileWrite = fs.createWriteStream(newPath);  // 可写流  
        fileRead.pipe(fileWrite);
        fileWrite.on("close",()=>{
            fs.unlinkSync(tempath);  // 上传成功把中转站的文件删除 
            res.json({
                err:"",
                msg:uploadUrl
            })
        })
    })
})

module.exports = router;